package com.pap.rbac.role.controller;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.stuxuhai.jpinyin.PinyinFormat;
import com.github.stuxuhai.jpinyin.PinyinHelper;
import com.pap.base.controller.BaseController;
import com.pap.base.util.date.DateUtils;
import com.pap.base.util.jackson.JacksonUtilss;
import com.pap.base.util.string.StringUtilss;
import com.pap.obj.vo.business.StatusFlagEnum;
import com.pap.obj.vo.response.ResponseVO;
import com.pap.rbac.agent.role.IRoleAgent;
import com.pap.rbac.agent.role.dto.RoleTreeNodeVO;
import com.pap.rbac.role.auto.entity.Role;

@RestController
@RequestMapping("/v1/rbac/role")
public class RoleController extends BaseController<Role, IRoleAgent> {

	private static Logger logger  =  LoggerFactory.getLogger(RoleController.class);
	
	@Resource(name = "roleAgent")
	@Override
	public void setService(IRoleAgent agent) {
		super.service = agent;
	}
	
	@RequestMapping(value = "/treejson", method = {RequestMethod.GET})
	public List<RoleTreeNodeVO> treeJSON(@RequestHeader(value = "clientLicenseId", defaultValue = "-1") String clientLicenseId,
			@RequestHeader(value = "loginUserId", defaultValue = "-1") String loginUserId) {
		//  全局默认角色的顶层编码为 -1 
		String globalParentId = "-1";
		return service.roleTreeJson(clientLicenseId, globalParentId);
	}
	
	/**
	 * 角色保存
	 * 必须输入参数为角色名称
	 */
	@Override
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/add", method = {RequestMethod.POST})
	public ResponseVO<Role> add(@RequestHeader(value = "clientLicenseId", defaultValue = "-1") String clientLicenseId,
			@RequestHeader(value = "loginUserId", defaultValue = "-1") String loginUserId,
			@RequestParam(value = "addJSON", required = true) String addJSON) throws Exception {
		
		ObjectMapper objectMapper = JacksonUtilss.getObjectMapper();
		Role role = objectMapper.readValue(addJSON, Role.class);
		role.setId(UUID.randomUUID().toString());
		
		
		if(role != null && 
				StringUtilss.isNotEmpty(role.getName())) {
			// 如果前端没有传递过来code值，则默认使用拼音代替
			if(StringUtilss.isEmpty(role.getCode())) {
				role.setCode(PinyinHelper.convertToPinyinString(role.getName(), "", PinyinFormat.WITHOUT_TONE));
			}
			role.setLevel("0");
			// 处理父级数据
			Role parentRole = service.selectByPrimaryKey(role.getParentId());
			if(parentRole != null) {
				// pathId
				if(StringUtilss.isNotEmpty(parentRole.getPathIds())) {
					role.setPathIds(parentRole.getPathIds() + "," + parentRole.getId());
				} else {
					role.setPathIds(parentRole.getId());
				}
				// pathCode
				if(StringUtilss.isNotEmpty(parentRole.getPathCodes())) {
					role.setPathCodes(parentRole.getPathCodes() + "," + parentRole.getCode());
				} else {
					role.setPathCodes(parentRole.getCode());
				}
				// pathName
				if(StringUtilss.isNotEmpty(parentRole.getPathNames())) {
					role.setPathNames(parentRole.getPathNames() + "," + parentRole.getName());
				} else {
					role.setPathNames(parentRole.getName());
				}
				// level
				if(StringUtilss.isNotEmpty(parentRole.getLevel())) {
					role.setLevel((Integer.parseInt(parentRole.getLevel()) + 1) + "");
				} else {
					role.setLevel("0");
				}
			} 
			role.setStatus(StatusFlagEnum.YES.getKey());
			role.setCreateIp("0.0.0.0");
			role.setCreateTime(DateUtils.getCurrDateTimeStr());
			role.setCreateUser(loginUserId);
			role.setClientLicenseId(clientLicenseId);
			role.setParentId(StringUtilss.isNotEmpty(role.getParentId()) == true ? role.getParentId() : "-1");
			
			int operationInt = service.insertSelective(role);
			
			return ResponseVO.successdata(operationInt);
			
		} else {
			return ResponseVO.validfail("入参异常，请判断是否含有角色名称");
		}

	}
	
	@Override
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/delete")
	public ResponseVO<Role> delete(@RequestHeader(value = "clientLicenseId", defaultValue = "-1") String clientLicenseId,
			@RequestHeader(value = "loginUserId", defaultValue = "-1") String loginUserId,
			@RequestParam(value = "deleteJSON", required = true) String deleteJSON) throws Exception {

		ObjectMapper objectMapper = JacksonUtilss.getObjectMapper();
		Role role = objectMapper.readValue(deleteJSON, Role.class);
		if(role != null && StringUtilss.isNotEmpty(role.getId())) {
			Map<Object, Object> pathIdsMap = new HashMap<Object, Object>();
			pathIdsMap.put("myLike_pathIds", role.getId());
			List<Role> roleList = service.selectListByMap(pathIdsMap);
			if(roleList != null && roleList.size() > 0) {
				return ResponseVO.validfail("请检查入参，此角色被其他角色所依赖!");
			} else {
				int operationInt = service.deleteByPrimaryKey(role.getId());
				return ResponseVO.successdata(operationInt);
			}
		} else { 
			return ResponseVO.validfail("入参异常，请判断是否含有角色编码");
		}
	}
	
	@Override
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/update", method = {RequestMethod.POST})
	public ResponseVO<Role> update(@RequestHeader(value = "clientLicenseId", defaultValue = "-1") String clientLicenseId,
			@RequestHeader(value = "loginUserId", defaultValue = "-1") String loginUserId,
			@RequestParam(value = "updateJSON", required = true) String updateJSON) 
					throws IOException, JsonParseException, JsonMappingException {
		
		ObjectMapper objectMapper = JacksonUtilss.getObjectMapper();
		Role role = objectMapper.readValue(updateJSON, Role.class);
		
		ResponseVO responseVO = service.updateAndCheckRole(role, loginUserId);
		return responseVO;
	}
}
